#!/usr/bin/env python
# -*- coding:utf-8 -*-
__author__ = 'walkingsky'


import requests
from models.runjs import decode
import datetime

import urllib3
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)


class HuobanApi:

    def __init__(self, username, password, space_id, dev=False):
        self.username = username
        self.password = password
        self.is_dev = False
        self.space_id = space_id
        #self.space_id = '4000000003068432'
        if (dev == True):
            self.is_dev = True
            self.token_url = 'http://token.dev.huoban.com/token'
            self.api_url = 'http://api.dev.huoban.com/v2/'
        else:
            self.token_url = 'https://api.huoban.com/paasapi/login'
            self.api_url = 'https://api.huoban.com/v2/'

    def login(self):
        '''
        登录伙伴
        '''
        params_str = '{"username":"' + self.username + '","password":"' + \
            self.password + '","client_id":1,"grant_type":"password"}'
        params_str = {'username': self.username, 'password': self.password,
                      'client_id': 1, 'grant_type': 'password'}
        # print(params_str)
        res = requests.post(self.token_url, json=params_str, verify=False)
        # print(res.text)
        res_json = res.json()
        if ('code' in res_json.keys()):
            # 登录失败
            print(res_json.get('message'))
            return False
        else:
            access_token = res_json.get('access_token')
            # print(access_token)
            self.token = decode(access_token)
            self.set_headers()
            return self.token

    def get_fund_ids(self):
        '''
        读取基金表格的基金code拼接字符串
        '''
        fund_str = ''
        url = 'https://api.huoban.com/paas/hbdata/item/view_item_list'
        # url = 'https://api.huoban.com/v2/item/table/T::fund/view/0/filter'
        params_str = {"offset": 0, "limit": 100, "table_id": 2100000014381329}
        headers = self.headers
        res = requests.post(url, json=params_str,
                            headers=headers, verify=False)
        # print(res.text)
        res_json = res.json()
        if ('code' in res_json.keys()):
            # 获取数据失败
            print(res_json.get('message'))
            return ''
        else:
            items = res_json.get('data').get('items')
            print(items)
            for item in items:
                fields = item.get('fields')
                for field in fields:
                    if field.get('alias') == 'fund.fund_code':
                        value = field.get('values')[0].get('value')
                        # print(value)
                        fund_str = fund_str + ',' + value

        return fund_str

    def set_headers(self):
        self.headers = {"User-Agent": "Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.9.1.6) ",
                        "Accept": "application/json",
                        "Accept-Language": "zh-CN,zh;q=0.9,en-US;q=0.8,en;q=0.7",
                        "Connection": "keep-alive",
                        "Authorization": "Bearer " + self.token,
                        "Content-Type": "application/json",
                        "X-Huoban-Return-Alias-Space-Id": self.space_id}

    def write_data(self, Datas):
        '''
        写入基金每天统计表格
        '''
        url = 'https://api.huoban.com/v2/item/table/T::fund_data2'
        for data in Datas:
            code = data.get('FCODE')
            name = data.get('SHORTNAME')
            date = str(data.get('GZTIME'))
            price = str(data.get('GSZ'))
            json_params = {"fields": {"F::fund_data2.fund_name": name, "F::fund_data2.fund_code": code,
                                      "F::fund_data2.date": date, "F::fund_data2.fund_price": price}}
            # print(json_params)
            #json_params = {"fields":{"2200000140161378":name ,"2200000140161379":code,"2200000140161339":date,"2200000140161340":price}}
            headers = self.headers
            res = requests.post(url, json=json_params,
                                headers=headers, verify=False)
            res_json = res.json()
            if ('code' in res_json.keys()):
                # 获取数据失败
                print(res_json.get('message'))
                # return False

    def write_history(self, data):
        '''
        写入基金历史表格
        '''
        url = 'https://api.huoban.com/v2/item/table/T::fund_history'

        code = data.get('code')
        #name = data.get('SHORTNAME')
        date = str(data.get('date'))
        price_1 = str(data.get('dwjz'))
        price_2 = str(data.get('ljjz'))
        json_params = {"fields": {"F::fund_history.fund_name": "", "F::fund_history.fund_code": code,
                                  "F::fund_history.date": date, "F::fund_history.fund_price_1": price_1, "F::fund_history.fund_price_2": price_2}}
        # print(json_params)
        #json_params = {"fields":{"2200000140161378":name ,"2200000140161379":code,"2200000140161339":date,"2200000140161340":price}}
        headers = self.headers
        res = requests.post(url, json=json_params,
                            headers=headers, verify=False)
        res_json = res.json()
        if ('code' in res_json.keys()):
            # 获取数据失败
            print(res_json.get('message'))
            # return False

    def write_stock(self, data):
        '''
        写入股票数据表格（不进行覆盖，有相同股票代码的，返回已有数据的itemid），并返回itemid
        data 为json 数据，{"name":"123","code":"123"}
        '''
        url = 'https://api.huoban.com/v2/item/table/T::stock/find'

        code = data.get('code')
        #name = data.get('name')
        print(code)

        # 先查看是否有该股票数据
        json_params = {"where": {"and": [{"query": {"or": [{"in": [
            code]}]}, "query_option_mappings":[-1], "field":"F::stock.stock_code"}]}, "offset": 0, "limit": 20}

        headers = self.headers
        res = requests.post(url, json=json_params,
                            headers=headers, verify=False)
        res_json = res.json()
        # print(res_json)
        if ('code' in res_json.keys()):
            print(res_json.get('message'))
            return
        else:
            total = int(res_json.get('filtered'))
            if (total == 0):
                return self.write_stock_write(data)
            else:
                print(res_json.get('items')[0].get('item_id'))
                return res_json.get('items')[0].get('item_id')

    def write_stock_write(self, data):
        '''
        写入股票数据表格,并返回itemid
        data 为json 数据，{"name":"123","code":"123","":""}
        '''
        url = 'https://api.huoban.com/v2/item/table/T::stock'

        code = data.get('code')
        name = data.get('name')

        json_params = {"fields": {
            "F::stock.stock_name": name, "F::stock.stock_code": code}}
        headers = self.headers
        res = requests.post(url, json=json_params,
                            headers=headers, verify=False)
        res_json = res.json()
        # print(res_json)
        if ('code' in res_json.keys()):
            # 获取数据失败
            print(res_json.get('message'))
            return False
        else:
            return res_json.get('item_id')

    def write_stock_time(self, data):
        '''
        写入股票数据表格
        data 为json 数据，{"name":"123","code":"123","":""}
        '''
        code = data.get('code')
        name = data.get('name')

        _time = datetime.date.today() - datetime.timedelta(days=1)
        _time_str = _time.strftime('%Y-%m-%d')

        headers = self.headers

        url = 'https://api.huoban.com/v2/item/table/T::stock_time/find'
        # {"where":{"and":[{"query":{"or":[{"in":["123"]}]},"query_option_mappings":[-1],"field":2200000163858393},{"field":2200000163858394,"query":{"eq":"yesterday"}}]},"offset":0,"limit":20}
        json_params = {"where": {"and": [{"query": {"or": [{"in": [code]}]}, "query_option_mappings":[
            -1], "field":"F::stock_time.stock_code"}, {"field": "F::stock_time.date", "query": {"eq": "yesterday"}}]}, "offset": 0, "limit": 20}
        # print(json_params)
        res = requests.post(url, json=json_params,
                            headers=headers, verify=False)
        res_json = res.json()
        # print(res_json)
        if ('code' in res_json.keys()):
            print(res_json.get('message'))
            return
        else:
            total = int(res_json.get('filtered'))
            if (total == 0):
                url = 'https://api.huoban.com/v2/item/table/T::stock_time'

                json_params = {"fields": {"F::stock_time.stock_name": name, "F::stock_time.stock_code": code,
                                          "F::stock_time.date": _time_str, "F::stock_time.count": "1"}}

                res = requests.post(url, json=json_params,
                                    headers=headers, verify=False)
                res_json = res.json()
                if ('code' in res_json.keys()):
                    # 获取数据失败
                    print(res_json.get('message'))
                    return False
            else:
                # print(res_json.get('items'))
                item_id = res_json.get('items')[0].get('item_id')
                count = res_json.get('items')[0].get('fields')[
                    3].get('values')[0].get('value')
                # print(count)
                url = 'https://api.huoban.com/v2/item/' + str(item_id)
                count = count + 1
                # print(count)
                json_params = {"fields": {"F::stock_time.count": count}}

                res = requests.put(url, json=json_params, headers=headers)
                res_json = res.json()
                if ('code' in res_json.keys()):
                    # 获取数据失败
                    print(res_json.get('message'))

    def write_fund_rank(self, data, table='fund_rank'):
        '''
        写入基金排行数据
        data 数据
        table 表格个别名
        '''
        url = 'https://api.huoban.com/v2/item/table/T::'+table

        code = data.get('code')
        name = data.get('name')
        stock = data.get('stock')

        rzf = data.get('rzf')
        zzf = data.get('zzf')
        a1yzf = data.get('a1yzf')
        a3yzf = data.get('a3yzf')
        a6yzf = data.get('a6yzf')
        a1nzf = data.get('a1nzf')
        a2nzf = data.get('a2nzf')
        a3nzf = data.get('a3nzf')
        jnzf = data.get('jnzf')
        lnzf = data.get('lnzf')

        json_params = {"fields": {"F::"+table+".fund_name": name, "F::"+table+".fund_code": code, "F::"+table+".stock": stock,
                                  "F::"+table+".rzf": rzf, "F::"+table+".zzf": zzf, "F::"+table+".a1yzf": a1yzf,
                                  "F::"+table+".a3yzf": a3yzf, "F::"+table+".a6yzf": a6yzf, "F::"+table+".a1nzf": a1nzf,
                                  "F::"+table+".a2nzf": a2nzf, "F::"+table+".a3nzf": a3nzf, "F::"+table+".jnzf": jnzf,
                                  "F::"+table+".lnzf": lnzf}}
        # print(json.dumps(json_params))
        headers = self.headers
        res = requests.post(url, json=json_params,
                            headers=headers, verify=False)
        res_json = res.json()
        print(res_json)
        if ('code' in res_json.keys()):
            # 获取数据失败
            print(res_json.get('message'))

    def clean_table(self, table):
        '''
        清空表格数据
        table 表格个别名
        '''
        url = 'https://api.huoban.com/v2/item/table/T::'+table+'/delete'
        json_params = {
            "view_id": 0
        }
        headers = self.headers
        res = requests.post(url, json=json_params,
                            headers=headers, verify=False)
        # print(res)

    def get_item_list(self,table_id:int=2100000014453089,field_id:int = 2200000140757589,limit:int=30,sort:str='desc'):
        '''
            获取表格数据
            参数：
            table_id:int 表格id
            field_id:int 排序的字段id  默认周排名字段2200000140757589，日排名字段2200000140725192
            limit:int 设定限定数据量
            sort:str 排序规则  'desc'倒序, 'asc'正序

            返回： json对象
        '''
        url = 'https://api.huoban.com/paas/hbdata/item/view_item_list'
        json_params = {
            "offset":0,
            "limit":limit,
            "permission_id":0,
            "filter":{},
            "search":{},
            "order_by":[{"sort":"desc","field":field_id}],
            "mode":"Service",
            "table_id":table_id}
        
        headers = self.headers
        res = requests.post(url, json=json_params,
                            headers=headers, verify=False)
        
        res_json = res.json()
        # print(res_json)
        if ('code' in res_json.keys()) and res_json.get('code') != 0:
            # 获取数据失败

            print(res_json.get('message'))
        else:
            return res_json
